{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G3MMAcssHTML"
      },
      "source": [
        "<link rel=\"stylesheet\" href=\"/site-assets/css/gemma.css\">\n",
        "<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=Google+Symbols:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200\" />"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f9673bd6"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://ai.google.dev/gemma/docs/capabilities/vision/video-understanding\"><img src=\"https://ai.google.dev/static/site-assets/images/docs/notebook-site-button.png\" height=\"32\" width=\"32\" />View on ai.google.dev</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/google/generative-ai-docs/blob/main/site/en/gemma/docs/capabilities/vision/video-understanding.ipynb\"\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://kaggle.com/kernels/welcome?src=https://github.com/google/generative-ai-docs/blob/main/site/en/gemma/docs/capabilities/vision/video-understanding.ipynb\"><img src=\"https://www.kaggle.com/static/images/logos/kaggle-logo-transparent-300.png\" height=\"32\" width=\"70\"/>Run in Kaggle</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/google/generative-ai-docs/main/site/en/gemma/docs/capabilities/vision/video-understanding.ipynb\"><img src=\"https://ai.google.dev/images/cloud-icon.svg\" width=\"40\" />Open in Vertex AI</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/google/generative-ai-docs/blob/main/site/en/gemma/docs/capabilities/vision/video-understanding.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qlsJnFBYSrkZ"
      },
      "source": [
        "# Video analysis with Gemma\n",
        "\n",
        "Video data is a rich source of information that can help you accomplish tasks and understand the world around you. Using Gemma with video data can help you understand spacial relationships, interpret human interactions, and assist with situational awareness. This tutorial shows you how to get started processing video data with Gemma using Hugging Face Transformers. The Transformers Python library provides a API for accessing pre-trained generative AI models, including Gemma. For more information, see the [Transformers](https://huggingface.co/docs/transformers/en/index) documentation.\n",
        "\n",
        "\n",
        "Note: Gemma 3 and later models support input of both images and text. Earlier versions of Gemma only support text input, except for some variants, including [PaliGemma](https://ai.google.dev/gemma/docs/setup).\n",
        "\n",
        "## Setup\n",
        "\n",
        "Before starting this tutorial, complete the following steps:\n",
        "\n",
        "* Get access to Gemma by logging into [Hugging Face](https://huggingface.co/google/gemma-3-4b-pt) and selecting **Acknowledge license** for a Gemma model.\n",
        "* Select a Colab runtime with sufficient resources to run\n",
        "  the Gemma model size you want to run. [Learn more](https://ai.google.dev/gemma/docs/core#sizes).\n",
        "* Generate a Hugging Face [Access Token](https://huggingface.co/docs/hub/en/security-tokens#how-to-manage-user-access-token) and add it to your Colab environment.\n",
        "\n",
        "### Configure Access Token\n",
        "\n",
        "Add your access token to Colab to enable downloading of Gemma models from the Hugging Face web site. Use the Colab **Secrets** feature to securely save your token without adding it to your working code.\n",
        "\n",
        "To add your Hugging Face Access Token as a Secret:\n",
        "\n",
        "1. Open the secrets tab by selecting the key icon on left side of the interface, or select **Tools > Command pallete**, type `secrets`, and press **Enter**.\n",
        "2. Select **Add new secret** to add a new secret entry.\n",
        "3. In the **Name** field, enter `HF_TOKEN`.\n",
        "4. In the **Value** field, enter the text of your Hugging Face Access Token.\n",
        "5. In the **Notebook access** field, select the switch to enable access.\n",
        "\n",
        "Once you have entered your Access Token as `HF_TOKEN` and value, you can access and set it within your Colab notebook environment using the following code:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ogSB3peYP1b4"
      },
      "outputs": [],
      "source": [
        "from google.colab import userdata\n",
        "from huggingface_hub import login\n",
        "\n",
        "# Login into Hugging Face Hub\n",
        "hf_token = userdata.get('HF_TOKEN') # If you are running inside a Google Colab\n",
        "login(hf_token)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2RgrZH4cP1b4"
      },
      "source": [
        "### Install Python packages\n",
        "\n",
        "Install the Hugging Face libraries required for running the Gemma model and making requests."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ty1cuOpoP1b4"
      },
      "outputs": [],
      "source": [
        "# Install Pytorch & other libraries\n",
        "%pip install \"torch>=2.4.0\"\n",
        "\n",
        "# Install a transformers version that supports Gemma 3n (>= 4.53.0)\n",
        "%pip install \"transformers>=4.53.0\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "C_NRd79RP1b4"
      },
      "source": [
        "## Prepare video data prompt\n",
        "\n",
        "Gemma models interpret video data by breaking it down into it's component parts, specifically as images of video frames and audio clips extracted from the video file. The following code example shows how to extract frames and audio from a video file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "SRNE_SBcWUkd"
      },
      "outputs": [],
      "source": [
        "!wget http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4 -O /content/video.mp4\n",
        "!mkdir /content/frames\n",
        "# extract frames from video at 1 frame per second (video is 15 seconds)\n",
        "!ffmpeg -i /content/video.mp4 -vf fps=1 /content/frames/%04d.jpg\n",
        "# extract audio from video as a single, 15-second clip\n",
        "!ffmpeg -i /content/video.mp4 -vn -c:a copy /content/audio.aac"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5eUZfA7uWYfX"
      },
      "source": [
        "Once you have extracted frames and audio from your video file into separate image files and audio files, you can assemble those components into a prompt. The following code example shows how to add the extracted video data to a prompt structure, in preparation for prompting the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Ch7Hs2t6qwtR"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "content = []\n",
        "\n",
        "for file in os.listdir(\"/content/frames\"):\n",
        "  content.append({\"type\": \"image\", \"url\": f\"/content/frames/{file}\"})\n",
        "\n",
        "content.append({\"type\": \"audio\", \"audio\": \"/content/audio.aac\"})\n",
        "content.append({\"type\": \"text\", \"text\": \"What is shown in this video?\"})\n",
        "\n",
        "messages = [\n",
        "    {\n",
        "        \"role\": \"user\",\n",
        "        \"content\": content\n",
        "    },\n",
        "]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9-bGXlDw5Hmh"
      },
      "source": [
        "For longer videos, you may need to reduce the number of frames per second captured to fit within Gemma model's context window. For audio clips, you should limit the total length of any audio clip to 30 seconds or less for best results."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NQ06l3iGP1b4"
      },
      "source": [
        "## Configure model\n",
        "\n",
        "When loading a Gemma model for use with audio data, configure the Transformer instance specifically for use with image and audio data. In particular, you must define a `processor` and `model` object using the `AutoProcessor` and `AutoModelForImageTextToText` classes, as shown in the following code example:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JoZ2ilfiP1b4"
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from transformers import AutoProcessor, AutoModelForImageTextToText\n",
        "\n",
        "GEMMA_MODEL_ID = \"google/gemma-3n-E4B-it\"\n",
        "\n",
        "processor = AutoProcessor.from_pretrained(GEMMA_MODEL_ID, device_map=\"auto\")\n",
        "model = AutoModelForImageTextToText.from_pretrained(\n",
        "            GEMMA_MODEL_ID, torch_dtype=\"auto\", device_map=\"auto\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5wnWGbLf1e1U"
      },
      "source": [
        "## Run video data request\n",
        "\n",
        "Once you have created a prompt with video data and configured the Gemma model `processor` and `model` objects, you can run the prompt to generate output. The following example code shows a request using a chat template, output generation, decoding of the response:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "isDs1jrN-Zh3"
      },
      "outputs": [],
      "source": [
        "input_ids = processor.apply_chat_template(\n",
        "        messages,\n",
        "        add_generation_prompt=True,\n",
        "        tokenize=True, return_dict=True,\n",
        "        return_tensors=\"pt\",\n",
        ")\n",
        "input_ids = input_ids.to(model.device, dtype=model.dtype)\n",
        "\n",
        "# Generate output from the model\n",
        "outputs = model.generate(**input_ids, max_new_tokens=128)\n",
        "\n",
        "# decode and print the output as text\n",
        "text = processor.batch_decode(\n",
        "    outputs,\n",
        "    skip_special_tokens=False,\n",
        "    clean_up_tokenization_spaces=False\n",
        ")\n",
        "print(text[0])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6f8ff452"
      },
      "source": [
        "## Next steps\n",
        "\n",
        "Build and explore more with Gemma models:\n",
        "\n",
        "* [Inference with images and video](https://github.com/google-gemini/gemma-cookbook/blob/main/Gemma/%5BGemma_3%5DInference_images_and_videos.ipynb)\n",
        "  in the Gemma Cookbook"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "name": "video-understanding.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
